//
//  RelatedListTable.m
//  SplitForce
//
//  Created by Ron Hess on 7/17/10.
//  Copyright 2010 Salesforce.com. All rights reserved.
//

#import "RelatedListTable.h"

 
@implementation RelatedListTable

#define FONTSize 16.0
#define	ROW_Height 33.0

@synthesize theLayout,detailItem,describe;

#pragma mark -
#pragma mark Initialization


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    
	SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];
	[app.rootViewController.client describeSObjectAsync:@"Account" withDelegate:self];
	[app.rootViewController.client describeLayoutAsync:@"account" withDelegate:self];
	return self;
}

-(void)describeSObjectReady:(ZKDescribeSObject *)results {
	describe = [results retain];
}

-(void)describeLayoutResultsReady:(ZKDescribeLayoutResult *)results {
	
	NSArray *layouts = [results layouts];
	
	theLayout = [layouts objectAtIndex:0];	// this is just the first layout, not a particular layout 
}

- (CGFloat)tableView:(UITableView *)tableView rowHeight:(NSIndexPath *)indexPath
{
    // Change the height if Edit Unknown Contact is the row selected
    return 33;//(indexPath.section==kUIEditUnknownContactRow) ? kUIEditUnknownContactRowHeight : tableView.rowHeight;    
}

- (ZKDescribeLayout *) objectLayout 
// get the layout, from cache or call the service and wait
{
	SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	NSArray *layouts = [[app.rootViewController.client describeLayout:@"account"] layouts];
	
	return [layouts objectAtIndex:0];	// this is just the first layout, not a particular layout 
}

- (void)setDetailItem:(id)newDetailItem {
    if (detailItem != newDetailItem) {
        [detailItem release];
		
		// requery the detail item to get related lists
		NSString *queryStr = @"Select ";
		queryStr = [queryStr stringByAppendingString: [describe getComaSepFieldList]];
		theLayout = [self objectLayout];
		// add in related lists queries 
		if ([[theLayout relatedLists] count] > 0) {
			for (ZKRelatedList *rl in [theLayout relatedLists] ) {			
				queryStr = [queryStr stringByAppendingFormat:@", (select %@ from %@ )", [rl columnsFieldNames],[rl name]];
			}
		}
		
		queryStr = [queryStr stringByAppendingFormat:@" from %@ where id = '%@' limit 1", 
					[describe name], [newDetailItem Id] ];	

		
		SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];
		NSLog(@"set detail Item relatedList %@", queryStr	);
		[app.rootViewController.client queryAsync:queryStr withDelegate:self];
	}
}
-(void)queryReady:(ZKQueryResult *)results {
	
	detailItem = [[[results records] objectAtIndex:0] retain];
		
	[super.tableView reloadData];
}

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad 
{
    [super viewDidLoad];
	CGRect r = self.tableView.frame;
	self.tableView.frame = CGRectMake(0,0,r.size.height,r.size.width);
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Override to allow orientations other than the default portrait orientation.
    return YES;
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[theLayout relatedLists] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSString *fldName = [[[ theLayout relatedLists] objectAtIndex:section] name];
	return [[detailItem queryResultValue:fldName] size];
}

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
	return [[[ theLayout relatedLists] objectAtIndex:section] label];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
	
    ZKRelatedList *rlist = [[ theLayout relatedLists] objectAtIndex:indexPath.section]; 
	NSString *fldName = [rlist name];
//	NSLog(@"section %d row %d",indexPath.section,indexPath.row);
//	NSLog(@"section %@ ",fldName);
	
	ZKQueryResult *rec = [detailItem queryResultValue:fldName];
	ZKSObject *row = [[rec records] objectAtIndex:indexPath.row ];
	
	//	NSLog(@"%@",[row description]);
	
	
	// layout the text based on the order of the related list 
	// TODO sort these records by the sort order of the related list, limit also.
	NSString	*tmp = @"";
	for (ZKRelatedListColumn *col in [rlist columns] ) {		
		tmp = [tmp stringByAppendingFormat:@"%@ ",[row fieldValue:[col name]] ];	
	}
	
	cell.textLabel.font = [UIFont systemFontOfSize:FONTSize];	
	cell.textLabel.text = tmp;//[@"" stringByAppendingFormat:@"%@",[row fieldValue:@"Name"] ];
    
    return cell;
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
	return ROW_Height; //returns floating point which will be used for a cell row height at specified row index  
}  

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

